<template>
  <div>
    <el-tabs v-model="activeName" v-if="showTabs">
      <el-tab-pane label="工程参数设置" name="first" v-if="this.showProjectParameter">
        <a-form :form="form" @submit="handleSubmit">
        <project-parameter ref="projectParameter" :projectParameters="this.projectParameterData"/>
        </a-form>
      </el-tab-pane>
      <el-tab-pane label="选择表" name="two" v-if="this.showSelectTable">
        <div>
          <el-row :gutter="20">
            <el-col :span="6">
              <h1>上传文件:</h1>
              <el-upload
                class="upload-demo"
                action="https://jsonplaceholder.typicode.com/posts/"
                accept=".pdm,.sql"
                :file-list="fileList"
                :on-change ="onchange"
                :http-request="getFile"
                style="margin-bottom: 20px;"
                :limit="limitNum"
              >
                <el-button size="small" type="primary">选择文件</el-button>
              </el-upload >
              <el-button size="small" type="success" @click="upload"  style="margin-bottom: 20px;">确认上传</el-button>
            </el-col>
            <el-col :span="6" v-if="showDbType==='1'">
              <h1 v-if="showDbType==='1'">选择数据库类型:</h1>
              <el-select v-model="dbTypeValue" placeholder="请选择" v-if="showDbType==='1'">
                <el-option
                  v-for="item in dbType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-row>


          <h1>选择表:</h1>
          <el-transfer
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入表中文或英文"
            :titles="['未选择的表', '已选择的表']"
            v-model="selectTable"
            :data="allTable"
            style="margin-bottom: 20px;"
          >
          </el-transfer>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-progress  :percentage="percentage" v-if="showProgress==true"></el-progress>
    <a-button type="primary" @click="handleSubmit">生成代码</a-button>
    <a-button type="primary" @click="loadLastProjectParameterValue()" v-if="this.showProjectParameter">获取最后工程参数</a-button>
    <a-button @click="returnList">返回</a-button>
  </div>
</template>

<script>
import request from "../utils/request";
import projectParameter from "../projectparameter/parent";
import {baseUrl, wsBaseUrl} from "../utils/env";
import { Message } from "element-ui";
export default {
  name: "run",
  components: {
    projectParameter
  },
  data(){
    return {
      file: {},
      fileList: [],
      selectTable:[],
      allTable:[],
      id:'',
      showTabs:false,
      activeName:'first',
      showProjectParameter:false,
      showSelectTable:false,
      isDataSource:'',
      projectParameterData: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
      projectParameterValue:{},
      percentage: 0,
      showProgress: false,
      message: '',
      websocket: '',
      downloadUrl:baseUrl+"/api/Runlog/downloadByLogNum",
      logNumber:'',
      dbTypeValue:'',
      dbType: [{
        value: 'mysql',
        label: 'MYSQL'
      }],
      showDbType:'0',
      limitNum:1,
    }
  },
  methods: {
    handleDownload(logNum) {
      console.log(logNum);
      window.open(
        `${this.downloadUrl}?logNum=${logNum}`
      )
    },
    onchange(file, fileList) {
      //console.log(file, fileList);
      let fileName = file.name.toLowerCase();
      console.log("filename:"+fileName);
      if(fileName.indexOf(".pdm")>=0){
        console.log("select pdm");
        this.showDbType = '0';
      }else if(fileName.indexOf(".sql")>=0){
        console.log("select sql");
        this.showDbType = '1';
      }
    },

    filterMethod(query, item){
      return item.key.indexOf(query) > -1 || item.label.indexOf(query) > -1;
    },
    getFile(item) {
      console.log(item.file)
      this.file = item.file
    },
    upload() {
      console.log('file type:'+this.file.type);
      const fd = new FormData()
      fd.append('filename', this.file)
      // const config = { headers: { 'Content-Type': 'multipart/form-data' }}
      // this.$request.post('/uploading', fd, config
      // ).then(response => {        this.$message.success(response.retCode)
      // })
      const  that = this;
      let uploadURL;
      if(this.showDbType==='0'){
         uploadURL = "/api/Project/uploadPdmFile";
      }else{
        if(this.dbTypeValue===''){
          this.$message('请选择数据库类型!');
          return;
        }
        fd.append("dbType",this.dbTypeValue);
        uploadURL = "/api/Project/uploadSqlFile"
      }
      request({
        method: "POST",
        url: uploadURL,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      }).then(response => {
        if (response.data.status == "1") {
          debugger;
          that.allTable = response.data.list;
          // response.data.list.forEach(function(c, index) {
          //   that.allTable.push({
          //     key: c.key,
          //     label: c.label
          //   });
          // });
        }
        this.$message(response.data.message);
      })
    },
    handleSubmit(e) {
      //e.preventDefault();
      debugger;
      this.form.validateFields((err, values) => {

        console.log(this.$refs["projectParameter"].data);
        //没有错误
        if (err==null) {
          console.log('no error: ', values);
          this.projectParameterValue = this.$refs["projectParameter"].data;
          this.makeCode();
        }else{
          this.activeName = "first";
        }
      });
    },
    //生成代码
    makeCode(){
      var tableCode=[];
      //循环选择表放到数组
      if(this.isDataSource=="1") {
        if (this.selectTable.length == 0) {
          this.$message("请选择表!");
          return;
        }
        debugger;
        for (var i = 0; i < this.selectTable.length; i++) {
          tableCode.push(this.selectTable[i]);
        }
      }
      this.$confirm("是否生成代码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        request({
          method: "POST",
          data:this.projectParameterValue,
          url: "/api/Project/run?projectId="+this.id+"&tableCode="+tableCode
        })
          .then(res => {
            if (res.data.status == "1") {
              // WebSocket

              if ('WebSocket' in window) {

                this.websocket = new WebSocket(wsBaseUrl + localStorage.sessionId + "/" + res.data.logNumber);
                this.logNumber = res.data.logNumber;
                this.initWebSocket()

              } else {

                this.$message('当前浏览器 Not support websocket')

              }
              //this.$message(res.data.message);
            } else {
              this.$message(res.data.message);
              return false;
            }
          })
          .catch(err => {
            console.log(err);
          });
      })
        .catch(err => {
          console.log(err);
        });
    },
    returnList(){
      this.$router.push({path: "/project/list"});
    },
    //装入表格数据
    loadProjectParameterData(projectId) {
      const that = this;
      request({
        method: "GET",
        url: `/api/ProjectParameter/listControlProperitesByProjectId?projectId=${projectId}`,
      })
        .then(res => {
          if (res.data.status == "1") {
            debugger;
            that.projectParameterData = res.data.list;
            console.log("projectParameterData:"+JSON.stringify(that.projectParameterData));
            if(res.data.count>0){
              that.showProjectParameter = true;
            }else{
              that.showProjectParameter = false;
            }
            if(that.showProjectParameter||that.showSelectTable){
              that.showTabs = true;
            }else{
              that.showTabs = false;
            }
            that.activieTab();
          } else {
            that.showProjectParameter = false;
            if(that.showProjectParameter||that.showSelectTable){
              that.showTabs = true;
            }else{
              that.showTabs = false;
            }
            that.activieTab();
            this.$message(res.data.message);
            return false;
          }

        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取当前用户最后工程参数
    loadLastProjectParameterValue() {
      const that = this;
      var userId = localStorage.userId;
      var projectId = this.id;
      request({
        method: "GET",
        url: `/api/ProjectParameter/getLastProjectParameterByProjectId?projectId=${projectId}&runUserId=${userId}`,
      })
        .then(res => {
          if (res.data.status == "1") {
            debugger;
            that.projectParameterValue = res.data.bean;
            console.log("projectParameterValue:"+JSON.stringify(that.projectParameterValue));
            //更新工程参数值
            this.$refs["projectParameter"].setPropertiesValue(that.projectParameterValue);
          } else {
            this.$message(res.data.message);
            return false;
          }

        })
        .catch(err => {
          console.log(err);
        });
    },
    activieTab(){
      if(this.showProjectParameter){
        this.activeName="first";
      }else{
        this.activeName="two";
      }
    },
    getLastProject(){

    },
    initWebSocket() {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage
      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage
      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },

    setErrorMessage() {
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    },

    setOnopenMessage() {
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
    },

    setOnmessageMessage(event) {
      // 根据服务器推送的消息做自己的业务处理
      console.log('服务端返回：' + event.data)
      debugger;
      let retVal = JSON.parse(event.data);
      if(retVal.status==='1'){
        //显示进度条
        if(!this.showProgress){
          this.showProgress = true;
        }
        //更新进度条及消息
        this.percentage = retVal.progress;
        this.message = retVal.message;
        if(this.percentage===100){
          //关闭进度条
          this.showProgress = false;
          //关闭ws
          this.closeWebSocket();
          //下载文件
          this.handleDownload(this.logNumber);
        }
      }else{
        //关闭进度条
        this.showProgress = false;
        //关闭ws
        this.closeWebSocket();
        //提示错误
        this.$message(retVal.message);
      }
    },
    setOncloseMessage() {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },

    onbeforeunload() {
      this.closeWebSocket();
    },
    closeWebSocket () {
      this.websocket.close()
    }
  },

  mounted() {
    this.id = this.$route.params.id;
    this.isDataSource = this.$route.params.isDataSource;
    console.log("isDataSource:"+this.isDataSource);
    if(this.isDataSource=="1"){
      this.showSelectTable = true;
      // this.showTabs =true;
    }else{
      this.showSelectTable = false;
    }
    this.loadProjectParameterData(this.id);
  }

}
</script>

<style scoped>

</style>
